package com.pine.manager.pineframework.trigger.impl;

import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysUserUpdateStatusRequest;
import com.pine.common.trigger.AbstractTriggerTemplate;
import com.pine.common.trigger.TriggerContext;
import com.pine.dao.pineframework.constants.StatusEnum;
import com.pine.dao.pineframework.entity.SysUser;
import com.pine.manager.core.TriggerTypeEnum;
import com.pine.manager.pineframework.SysUserManager;
import com.pine.manager.pineframework.bo.SysUserBo;
import com.pine.manager.pineframework.convertors.SysUserConvertor;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 用户修改状态触发器
 *
 * @author pine manage
 * @since 2024-08-16
 */
@Component
@Slf4j
public class SysUserUpdateStatusTrigger extends AbstractTriggerTemplate<SysUserUpdateStatusRequest, Boolean> {

    @Resource
    private SysUserManager sysUserManager;

    @Resource
    private SysUserConvertor sysUserConvertor;

    private SysUserBo oldSysUserBo;

    public SysUserUpdateStatusTrigger() {
        super(TriggerTypeEnum.SYS_USER_UPDATE_STATUS);
    }

    @Override
    protected void before(TriggerContext<SysUserUpdateStatusRequest> triggerContext) {
        SysUserUpdateStatusRequest request = triggerContext.getTriggerRequest();
        Long userId = request.getId();
        oldSysUserBo = sysUserManager.getOneByUniqueKey(userId, SysUser::getId);
        if (Objects.isNull(oldSysUserBo)) {
            throw new BusinessException(ExceptionCodeEnum.USER_NOT_EXIST);
        }
    }

    /**
     * 触发
     *
     * @param triggerContext 触发上下文
     * @return 触发结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean trigger(TriggerContext<SysUserUpdateStatusRequest> triggerContext) {
        // 设置状态
        SysUserUpdateStatusRequest request = triggerContext.getTriggerRequest();
        oldSysUserBo.setStatus(StatusEnum.of(request.getStatus()));

        // 修改数据库
        SysUser sysUser = sysUserConvertor.entityBoToEntity(oldSysUserBo);
        return sysUserManager.updateById(sysUser);
    }
}
